import Layout from '@/views/layout';
import store from '@/store';

let routes = [{
	path: '/',
	redirect: '/login'
}, {
	path: '/login',
	component: () => import('@/views/login/index.vue')
}, {
	path: '/dashboard',
	component: Layout,
	children: [{
		path: '',
		component: () => import('@/views/dashboard/index.vue')
	}],
	meta: {
		isMenu: true
	}
}, {
	path: '/error',
	component: () => import('@/views/error/index.vue')
}];

let permissions = store.state.global.permissions.concat();
let queue = [];
let i = 0;
let root = null;
while(i < permissions.length || queue.length > 0) {
	if(queue.length == 0) {
		let permission = permissions[i++];
		root = {
			path: '/' + permission.id.replace(/:/g, "/"),
			component: Layout,
			children: [],
			meta: {
				isMenu: true,
				permissionId: permission.id
			}
		}
		if(permission.isOpen) {
			root.children.push({
				path: '',
				component: () => import('@/views/' + permission.id.replace(/:/g, "/") + "/index.vue"),
				meta: {
					isMenu: true,
					permissionId: permission.id
				}
			});
		}
		routes.push(root);
		queue.push(permission);
		continue;
	}
	let permission = queue.shift();
	if(permission.children && permission.children.length > 0) {
		permission.children.forEach(child => {
			if(child.isOpen) {
				let path = '/' + child.id.replace(/:/g, '/');
				path = path.replace(root.path + "/", '');
				root.children.push({
					path: path,
					component: () => import('@/views/' + child.id.replace(/:/g, "/") + "/index.vue"),
					meta: {
						isMenu: true,
						permissionId: child.id
					}
				});
			}
			queue.push(child);
		});
	}
}


export default routes;